'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useState,
} from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import diff from 'microdiff';
import type {
  IConfigUser,
  IDifference,
  IUpdateUserConfigBody,
} from '@/interfaces';
import type { TBody } from '@/types';
import { updateUserConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { ConfigAdminContext } from '@/contexts/admin/config';
import { getDiffData, getFilterData, isEmpty, isNum } from '@/lib/tool';

export default function UpdateConfigUser({
  details,
}: {
  details: IConfigUser;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    rootId: string;
  }>({
    rootId: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const queryClient = useQueryClient();
  const context = useContext(ConfigAdminContext);

  const updateUserConfigMutation = useMutation(
    async (variables: TBody<IUpdateUserConfigBody>) => {
      await updateUserConfig(variables);
      await queryClient.invalidateQueries([
        '/configs',
        `/${context.updateItem?.id}`,
      ]);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        rootId: details.rootId + '',
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          rootId: details.rootId,
        },
        {
          rootId: parseInt(form.rootId),
        },
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateUserConfigMutation.mutateAsync({
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateUserConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  function checkForm() {
    const { rootId } = form;

    if (!rootId) {
      throw '论坛管理员 Id 不能为空';
    } else if (!isNum(rootId)) {
      throw '请正确输入论坛管理员 Id';
    }
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">论坛管理员 Id</label>
            <input
              type="text"
              className="form-control"
              name="rootId"
              value={form.rootId}
              onChange={onChangeForm}
              aria-describedby="rootId"
              placeholder="请输入论坛管理员 Id"
            />
          </div>

          <button
            type="submit"
            disabled={updateUserConfigMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateUserConfigMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
